package cn.itcast.dao_impl;

import cn.itcast.dao.IAdminDao;
import cn.itcast.db_util.JdbcUtil;
import cn.itcast.entity.Admin;

import java.net.URI;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created 吴海杰 on 2017/2/28.
 */
public class AdminDao implements IAdminDao{
    private Connection con;
    private PreparedStatement pstmt;
    private ResultSet rs;


    public Admin findByNameAndPwd(Admin admin){
        String sql="SELECT  *FROM admin WHERE userName=? AND pwd=?;";
        Admin ad=null;
        try {
            con= JdbcUtil.getConnection();
            pstmt=con.prepareStatement(sql);
            pstmt.setString(1,admin.getUserName());
            pstmt.setString(2,getPwd());
            rs=pstmt.executeQuery();
            if (rs.next()){
                 ad=new Admin();
                ad.setId(rs.getInt("id"));
                ad.setUserName(rs.getString("userName"));
                ad.setPwd(rs.getString("pwd"));
            }
            return ad;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new  RuntimeException(e);
        }finally {
            JdbcUtil.close(con,pstmt,null);
        }



    }
    public void save(Admin admin){
        String sql="INSERT INTO admin(userName, pwd) VALUES (?,?);";
        try {
            con=JdbcUtil.getConnection();
            pstmt=con.prepareStatement(sql);
            pstmt.setString(1,admin.getUserName());
            pstmt.setString(2,getPwd());
        } catch (SQLException e) {
            e.printStackTrace();
            throw new  RuntimeException(e);
        } finally {
            JdbcUtil.close(con,pstmt,null);
        }


    }
    public void userExists(String name){
        String sql="SELECT id FROM admin WHERE userName=?;";
        try {
            con=JdbcUtil.getConnection();
            pstmt=con.prepareStatement(sql);
            pstmt.setString(1,admin.getUserName());
        } catch (SQLException e) {
            e.printStackTrace();
            throw new  RuntimeException(e);
        } finally {
            JdbcUtil.close(con,pstmt,rs);
        }


    }
}
